package springboot.study.project.util.es;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;

import java.net.InetAddress;

/**
 * @ClassName: EsClientPoolFactory
 * @Description: Elasticsearch客户端工厂类
 * @Author: baoxia
 * @Date: 2020-07-05 13:19
 * @Version: 1.0
 **/
public class EsClientPoolFactory implements PooledObjectFactory<TransportClient> {

    /**
     * ES集群名称
     */
    @Value("${es.clustername}")
    private String clusterName;
    /**
     * ES服务主机地址
     */
    @Value("${es.host}")
    private String host;
    /**
     * ES服务主机地址（集群）
     */
    @Value("${es.hosts}")
    private String hostsStr;
    /**
     * ES服务端口号
     */
    @Value("${es.port}")
    private int port;

    @Override
    public void activateObject(PooledObject<TransportClient> arg0) throws Exception {
        System.out.println("activateObject");
    }

    /**
     * 销毁对象
     */
    @Override
    public void destroyObject(PooledObject<TransportClient> pooledObject) throws Exception {
        TransportClient client = pooledObject.getObject();
        client.close();
    }

    /**
     * 生产对象
     */
    @Override
    public PooledObject<TransportClient> makeObject() throws Exception {
        TransportClient client = null;
        // 配置设置对象，指定集群的名称
        Settings settings = Settings.builder().put("cluster.name", clusterName).build();
        // ES集群
        String[] hosts = hostsStr.replace(" ", "").split(",");

        try {
            // 创建访问es服务器的客户端实例
            client = new PreBuiltTransportClient(settings);
            // 配置其ES集群节点的IP和端口号（注意使用的TCP协议进行链接的所以使用的9300）
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
            // client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hosts[0]), port));
            // client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hosts[1]), port));
            // client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hosts[2]), port));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new DefaultPooledObject<TransportClient>(client);
    }

    @Override
    public void passivateObject(PooledObject<TransportClient> arg0) throws Exception {
        System.out.println("passivateObject");
    }

    @Override
    public boolean validateObject(PooledObject<TransportClient> arg0) {
        return true;
    }
}
